package rest

import (
	"fmt"
	"net/url"
	"path"

	"gitee.com/youkelike/ziam/zapi/scheme"
)

func defaultServerURLFor(config *Config) (*url.URL, string, error) {
	hasCert := config.HasCertAuth()
	defaultTLS := hasCert && !config.Insecure
	if defaultTLS {
		config.Host = config.SecureHost
	}

	// config.APIPath 默认是空字符串
	if config.GroupVersion != nil {
		return DefaultServerURL(config.Host, config.APIPath, *config.GroupVersion, defaultTLS)
	}

	return DefaultServerURL(config.Host, config.APIPath, scheme.GroupVersion{}, defaultTLS)
}

func DefaultServerURL(host, apiPath string, groupVersion scheme.GroupVersion,
	defaultTLS bool) (*url.URL, string, error) {
	hostURL, err := url.Parse(host)
	// 当 url 解析出错，或者 url 中没有 scheme 或 host 的时候，重新构造默认的 url
	if err != nil {
		return nil, "", err
	}

	if hostURL.Path != "" {
		return nil, "", fmt.Errorf("host must be a host:port pair: %q", host)
	}

	// 手动规范化，去掉 host 中域名端口后的所有内容
	hostURL.Path = "/"
	hostURL.RawQuery = ""
	hostURL.Fragment = ""

	// 只用 apiPath 和 version 来构造 path 前缀部分
	versionedAPIPath := path.Join("/", apiPath, groupVersion.Version)

	return hostURL, versionedAPIPath, nil
}
